import axios from 'axios'
import qs from 'qs'

var instance = axios.create({
  baseURL: 'http://localhost:8000',
});

instance.interceptors.request.use(function (config) {
  let authToken = localStorage.getItem('token') || ''
  let url = config.url
  if (url.indexOf('auth') > -1) config.headers.Authorization = ""
  if (authToken) config.headers.Authorization = `JWT ${authToken}`
  if (config.method == 'post' && (config[0] == undefined || config[0].toLowerCase() != 'json')) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    config.data = qs.stringify(config.data, {
      arrayFormat: 'repeat'
    });
  }
  if (config.method == 'get') {
    config.url = config.url + '?' + qs.stringify(config.data, {
      arrayFormat: 'repeat'
    })
  }
  return config;
}, function (err) {
  return Promise.reject(err);
})

instance.interceptors.response.use(function (response) {
  let token = localStorage.getItem('token') || ''
  if (!token) location.replace('#/login')
  return response.data
}, function (error) {
  // location.replace('#/login')
  return error
});

export default instance;